package org.hilo.boot.app.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;

import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * 使用Swagger2 自动生成 API文档
 * 
 * @author zollty
 * @since 2018-2-28
 */
@Configuration
@EnableSwagger2
@ConditionalOnProperty(name = Swagger2Config.BASE_PAKAGE)
public class Swagger2Config {
    
    static final String BASE_PAKAGE = "hilo.swagger.base-packages";
    @Value("${" + BASE_PAKAGE + "}")
    private String basePackages;

    @Bean
    public Docket createRestApi() {
        ApiSelectorBuilder builder = new Docket(DocumentationType.SWAGGER_2).select();
//        for (String basePackage : basePackages) {
//            // api接口包扫描路径
//            builder.apis(Swagger2Config.basePackage(basePackage));
//        }
        // api接口包扫描路径，支持多个以逗号分隔
        builder.apis(Swagger2Config.basePackage(basePackages));
        basePackages = null;
        // 可以根据url路径设置哪些请求加入文档，忽略哪些请求
        return builder.paths(PathSelectors.any()).build().apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
             // 设置文档的标题等信息
            .title("Hilo RESTful API")
            .description("Hilo：企业级应用基础开发框架")
            .termsOfServiceUrl("https://github.com/springfox/springfox")
            .version("1.0")
            .build();
    }
    

    /**
     * 处理包路径配置规则,支持多路径扫描匹配以逗号隔开
     * @param basePackage 扫描包路径
     */
    public static Predicate<RequestHandler> basePackage(final String basePackage) {
        return new Predicate<RequestHandler>() {
            @Override
            public boolean apply(RequestHandler input) {
                return declaringClass(input).transform(handlerPackage(basePackage)).or(true);
            }
        };
    }
    
    private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) {
        return new Function<Class<?>, Boolean>() {
            @Override
            public Boolean apply(Class<?> input) {
                for (String strPackage : basePackage.split(",")) {
                    boolean isMatch = input.getPackage().getName().startsWith(strPackage.trim());
                    if (isMatch) {
                        return true;
                    }
                }
                return false;
            }
        };
    }
    
    private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
        return Optional.fromNullable(input.declaringClass());
    }

}
